﻿using CardMonitor.Model;
using CardMonitor.Utils;
using CardMonitor.Windows;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Office.Core;
using Excel = Microsoft.Office.Interop.Excel;
using DotNetSpeech;
using System.Windows.Threading;
using System.IO;
using ZXing.QrCode;
using ZXing;
using ZXing.QrCode.Internal;

namespace CardMonitor.Pages
{
    /// <summary>
    /// Index.xaml 的交互逻辑
    /// </summary>
    public partial class Index : Page
    {
        NewCardInfo newCardInfo = null;
        CardInfo objIDCardInfo = null;
        Page currentPage = null;
        MainWindow mainWindow = null;
        SpVoice speech = new SpVoice();
        string[] CardInfo = new string[30];
        //IntPtr icdev = IntPtr.Zero;
        //int st;
        //int sysLanguage = 0;
        IntPtr icPtr = IntPtr.Zero;
        public Index(MainWindow _win)
        {
            InitializeComponent();
            currentPage = this;
            string WorkMode = (string)App.getConfig().WorkMode;
            if (WorkMode.Equals("0"))
            {
                CardDeviceUtil.ReceiveCard();//回收卡片
            }
           
            mainWindow = _win;

            this.Loaded += Page_loaded;
       

       
        }
        
        private void showMessage(String message)
        {
            InfoWindow infoWindow = new InfoWindow(message);
            infoWindow.Owner = mainWindow;
            infoWindow.ShowDialog();
        }
        private void Page_loaded(object sender, RoutedEventArgs e)
        {
            
        }

        private void doCard(object sender, RoutedEventArgs e)//读卡
        {
            string cardDevice = (string)App.getConfig().IDCardDevice;
            if (!"1".Equals(cardDevice))
            {
                goMakeCard((string)App.getConfig().IDCardCode,"","");
                return;
            }
           int code= NewIDcardread.CardAuthentication();//身份认证
            if (code == 1)
            {

                newCardInfo = NewIDcardread.ReadIDcard();
                if (newCardInfo == null)
                {
                    showMessage("未读取到身份证信息");
                }
                else
                {
                    goMakeCard(newCardInfo.CardNo, newCardInfo.Name, newCardInfo.driverMacCard);
                }
            }
            else {

                showMessage("请重新放置身份证");

            }

           
        }

        private void goMakeCard(String cardCode, String name, String driverMacCard)
        {
            HttpPostWindow httpPostWindow = new HttpPostWindow();
            httpPostWindow.Owner = mainWindow;

            JObject paramJSON = new JObject();
            paramJSON.Add("driverCard", cardCode);
            paramJSON.Add("operation", "forMakeCard");
            paramJSON.Add("driverMacCard", driverMacCard);
            httpPostWindow.setParamObject(paramJSON);

            httpPostWindow.setOperation(HttpPostWindow.OperationType.getBillByCard.ToString());
            bool result = (bool)httpPostWindow.ShowDialog();
            if (!result)
            {
                string message = httpPostWindow.getMessage();
                if (null == message || "".Equals(message))
                {
                    message = "未查询到单据";
                }
                speech.Speak(message, SpeechVoiceSpeakFlags.SVSFlagsAsync);

                showMessage(message);

                return;
            }
            mainWindow.Speak("请仔细核对计划业务类型及计划信息，确认无误后点击对应业务报到按钮，若无对应业务请返回首页");
            JArray resultArray = httpPostWindow.getResultArray();
            List<BillModel> billModel = JsonConvert.DeserializeObject<List<BillModel>>(resultArray.ToString());
            SaleCards card = new SaleCards(billModel, mainWindow);
/*            if (null != image)
            {
                card.setPersonImage(image);
            }*/
            NavigationService.GetNavigationService(this).Navigate(card);

        }

      
        private void doQuery(object sender, RoutedEventArgs e)
        {
        }

        private void doPrint(object sender, RoutedEventArgs e)
        {


            //身份证选择
            //PrintOptionPage printOptionPage = new PrintOptionPage(mainWindow);
            //NavigationService.GetNavigationService(this).Navigate(printOptionPage);
            string cardDevice = (string)App.getConfig().IDCardDevice;
            if (!"1".Equals(cardDevice))
            {
                goBillPrint((string)App.getConfig().IDCardCode);
                return;
            }

            string sMsg = string.Empty;
            String sPath = System.Environment.CurrentDirectory + "\\";

            try
            {
                //读身份证对象
                objIDCardInfo = IDCardReader.ReadCardInfo(0, out sMsg, sPath);
                if (!string.IsNullOrEmpty(sMsg))
                {
                    showMessage(sMsg);
                }
            }
            catch (Exception ex)
            {
                showMessage("身份证读取失败");
            }

            if (objIDCardInfo != null)
            {
                System.IO.MemoryStream objMSPhoto = new System.IO.MemoryStream(objIDCardInfo.ArrPhotoByte, 0, objIDCardInfo.ArrPhotoByte.Length);

                ImageBrush imageBrush = new ImageBrush();
                ImageSourceConverter imageSourceConverter = new ImageSourceConverter();
                imageBrush.ImageSource = (ImageSource)imageSourceConverter.ConvertFrom(objMSPhoto);

                //goMakeCard(objIDCardInfo.CardNo, objIDCardInfo.Name, imageBrush);

                //byte[] Photo = Convert.FromBase64String(CardInfo[14]);
                //MemoryStream ms = new MemoryStream(Photo);
                //System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
                System.Drawing.Image image = null;
                goBillPrint(objIDCardInfo.CardNo);
            }
        }
        private void goBillPrint(String facId)
        {
            HttpPostWindow httpPostWindow = new HttpPostWindow();
            httpPostWindow.Owner = mainWindow;

            JObject paramJSON = new JObject();
            paramJSON.Add("facId", facId);
            paramJSON.Add("operation", "clientPrint");
            paramJSON.Add("printDuration",App.getConfig().printDuration);
            httpPostWindow.setParamObject(paramJSON);

            httpPostWindow.setOperation(HttpPostWindow.OperationType.getBillsByCardForPrint.ToString());
            bool result = (bool)httpPostWindow.ShowDialog();
            if (!result)
            {
                string message = httpPostWindow.getMessage();
                if (null == message || "".Equals(message))
                {
                    message = "请到人工窗口打印";
                }
                speech.Speak(message, SpeechVoiceSpeakFlags.SVSFlagsAsync);

                showMessage(message);

                return;
            }
            JArray resultArray = httpPostWindow.getResultArray();
          //  MessageBox.Show(resultArray.ToString());
        //    Console.WriteLine(resultArray.ToString());
        

        List<BillModel> bills = JsonConvert.DeserializeObject<List<BillModel>>(resultArray.ToString());
            if(null == bills || bills.Count == 0)
            {
                showMessage("未查询到单据");
                return;
            }
            PrintPage printPage = new PrintPage(bills, mainWindow);
            NavigationService.GetNavigationService(this).Navigate(printPage);

            //PrintItemPage printItemPage = new PrintItemPage(mainWindow, bills[0]);
            //NavigationService.GetNavigationService(this).Navigate(printItemPage);
        }

        //private void doAccount(object sender, RoutedEventArgs e)
        //{
        //    String autoSettleAccounts = App.getConfig().AutoSettleAccounts;
        //    if (!"1".Equals(autoSettleAccounts))
        //    {
        //        showMessage("请到人工窗口结算");
        //        return;
        //    }
        //    BillModel billModel = new BillModel();
        //    ReadCardWindow readCardWindow = new ReadCardWindow();
        //    readCardWindow.billModel = billModel;
        //    readCardWindow.Owner = mainWindow;
        //    bool result = (bool)readCardWindow.ShowDialog();
        //    if (result)
        //    {
        //        string guid = billModel.FacId;
        //        if(null == guid || "".Equals(guid))
        //        {
        //            showMessage("读卡失败,请将IC卡插入");
        //            return;
        //        }
        //        HttpPostWindow httpPostWindow = new HttpPostWindow();
        //        httpPostWindow.Owner = mainWindow;

        //        JObject paramJSON = new JObject();
        //        paramJSON.Add("guid", billModel.FacId);
        //        paramJSON.Add("operation", "forAccount");//forAccount
        //        paramJSON.Add("busiType", "all");//buy or sale
        //        httpPostWindow.setParamObject(paramJSON);

        //        httpPostWindow.setOperation(HttpPostWindow.OperationType.getBillByCardGuidForAccount.ToString());
        //        result = (bool)httpPostWindow.ShowDialog();
        //        if (!result)
        //        {
        //            CardDeviceUtil.PopupCard();
        //            string message = "查询结算单据失败,请到人工窗口办理";
        //            showMessage(message);
        //            return;
        //        }
        //        JObject resultObj = httpPostWindow.getResultObject();
        //        BillModel bill = JsonConvert.DeserializeObject<BillModel>(resultObj.ToString());
        //        string density = App.getConfig().density;
        //        double midu = double.Parse(density);

        //        Account accountPage = new Account(bill, mainWindow);
        //        NavigationService.GetNavigationService(this).Navigate(accountPage);
        //        //CardDeviceUtil.ReceiveCard();
        //        //showMessage("收卡完成");
        //        //NavigationService.GetNavigationService(this).GoBack();
        //    }
        //    else
        //    {
        //        showMessage("读卡失败");
        //        mainWindow.Speak("读卡失败");
        //    }
        //}
        private void doAccount(object sender, RoutedEventArgs e)
        {
            String autoSettleAccounts = App.getConfig().AutoSettleAccounts;
            if (!"1".Equals(autoSettleAccounts))
            {
                showMessage("请到人工窗口结算");
                return;
            }
            string cardDevice = (string)App.getConfig().IDCardDevice;
            if (!"1".Equals(cardDevice))
            {
                goAccount((string)App.getConfig().IDCardCode);
                return;
            }

            string sMsg = string.Empty;
            String sPath = System.Environment.CurrentDirectory + "\\";

            try
            {
                //读身份证对象
                objIDCardInfo = IDCardReader.ReadCardInfo(0, out sMsg, sPath);
                if (!string.IsNullOrEmpty(sMsg))
                {
                    showMessage(sMsg);
                }
            }
            catch (Exception ex)
            {
                showMessage("身份证读取失败");
            }

            if (objIDCardInfo != null)
            {
                goAccount(objIDCardInfo.CardNo);
            }

        }
        private void doReports(object sender, RoutedEventArgs e)//多仓叫号
        {
            // 身份证选择
            //CardOptionPage cardOptionPage = new CardOptionPage(mainWindow);
            //NavigationService.GetNavigationService(this).Navigate(cardOptionPage);

            string cardDevice = (string)App.getConfig().IDCardDevice;//
            if (!"1".Equals(cardDevice))
            {
                goMakeReports((string)App.getConfig().IDCardCode, "");//----------
                return;
            }
            string sMsg = string.Empty;
            String sPath = System.Environment.CurrentDirectory + "\\";

            try
            {
                //读身份证对象
                objIDCardInfo = IDCardReader.ReadCardInfo(0, out sMsg, sPath);
                if (!string.IsNullOrEmpty(sMsg))
                {
                    showMessage(sMsg);
                }
            }
            catch (Exception ex)
            {
                showMessage("身份证读取失败");
            }

            if (objIDCardInfo != null)
            {
                System.IO.MemoryStream objMSPhoto = new System.IO.MemoryStream(objIDCardInfo.ArrPhotoByte, 0, objIDCardInfo.ArrPhotoByte.Length);

                ImageBrush imageBrush = new ImageBrush();
                ImageSourceConverter imageSourceConverter = new ImageSourceConverter();
                imageBrush.ImageSource = (ImageSource)imageSourceConverter.ConvertFrom(objMSPhoto);

                goMakeReports(objIDCardInfo.CardNo, objIDCardInfo.Name, imageBrush);
            }
        }
        private void goMakeReports(String cardCode, String name, ImageBrush image = null)//多仓叫号
        {
            HttpPostWindow httpPostWindow = new HttpPostWindow();
            httpPostWindow.Owner = mainWindow;

            JObject paramJSON = new JObject();
            paramJSON.Add("driverCard", cardCode);
            paramJSON.Add("operation", "forMakeCard");
            httpPostWindow.setParamObject(paramJSON);

            httpPostWindow.setOperation(HttpPostWindow.OperationType.getMakeReports.ToString());
            bool result = (bool)httpPostWindow.ShowDialog();//false
            if (!result)
            {
                string message = httpPostWindow.getMessage();//系统异常
                if (null == message || "".Equals(message))
                {
                    message = "未查询到单据";
                }
                speech.Speak(message, SpeechVoiceSpeakFlags.SVSFlagsAsync);//弹窗系统异常

                showMessage(message);

                return;
            }
            mainWindow.Speak("请仔细核对计划业务类型及计划信息，卸车业务请确认好货源地，确认无误后点击对应业务报到按钮，若无对应业务请返回首页");

            //将卡片移动至读卡区域
            //App.getGlobalVariables().cardDeviceComm.SendHexData("F2 00 00 03 43 32 31 03 B2");
            //CardDeviceUtil.MoveCardToReadPosition();
            JArray resultArray = httpPostWindow.getResultArray();//JSON数组
            //JObject resultObject = httpPostWindow.getResultObject();
            List<BillModel> billModel = JsonConvert.DeserializeObject<List<BillModel>>(resultArray.ToString());

            MakeReports card = new MakeReports(billModel, mainWindow);
            if (null != image)
            {
                card.setPersonImage(image);
            }
            NavigationService.GetNavigationService(this).Navigate(card);
        }


        private void goAccount(string iDCardCode)//结算
        {
            BillModel billModel = new BillModel();
            HttpPostWindow httpPostWindow = new HttpPostWindow();
            httpPostWindow.Owner = mainWindow;

            JObject paramJSON = new JObject();
            paramJSON.Add("facId", iDCardCode);
            paramJSON.Add("operation", "forAccount");//forAccount
            paramJSON.Add("busiType", "all");//buy or sale
            httpPostWindow.setParamObject(paramJSON);

            httpPostWindow.setOperation(HttpPostWindow.OperationType.getBillByCardGuidForAccount.ToString());
            bool result = (bool)httpPostWindow.ShowDialog();
            if (!result)
            {
                //CardDeviceUtil.PopupCard();
                string message = "查询结算单据失败,请到人工窗口办理";
                showMessage(message);
                return;
            }
            JObject resultObj = httpPostWindow.getResultObject();
            BillModel bill = JsonConvert.DeserializeObject<BillModel>(resultObj.ToString());
            Account accountPage = new Account(bill, mainWindow);
            NavigationService.GetNavigationService(this).Navigate(accountPage);
        }

        private void test_print(object sender, RoutedEventArgs e)
        {
            //PrintUtils.printBill("tplBuyIn", new BillModel());
        }

        private void doConfirm(object sender, RoutedEventArgs e)
        {
            // 身份证选择
            //CardOptionPage cardOptionPage = new CardOptionPage(mainWindow);
            //NavigationService.GetNavigationService(this).Navigate(cardOptionPage);


            string cardDevice = (string)App.getConfig().IDCardDevice;
            if (!"1".Equals(cardDevice))
            {
                goConfirm((string)App.getConfig().IDCardCode);
                return;
            }

            string sMsg = string.Empty;
            String sPath = System.Environment.CurrentDirectory + "\\";

            try
            {
                //读身份证对象
                //objIDCardInfo = IDCardReader.ReadCardInfo(0, out sMsg, sPath);
                StringBuilder IdCardInfo = new StringBuilder(409600);
                int ret = CommonInterface.SdtReadCard(0, 1, IdCardInfo, 0);
                if (ret != 0)
                {
                    MessageBox.Show("读取证件信息失败，错误代码：" + ret.ToString());
                    return;
                }

                CardInfo = IdCardInfo.ToString().Split(':');
                if (!string.IsNullOrEmpty(sMsg))
                {
                    showMessage(sMsg);
                }
            }
            catch (Exception ex)
            {
                showMessage("身份证读取失败");
            }

            if (CardInfo != null)
            {


                //byte[] Photo = Convert.FromBase64String(CardInfo[14]);
                //MemoryStream ms = new MemoryStream(Photo);
                //System.Drawing.Image image = System.Drawing.Image.FromStream(ms);
                System.Drawing.Image image = null;
                goConfirm(CardInfo[9], image);
            }
        }
        private void goConfirm(String cardCode, System.Drawing.Image image = null)
        {
            HttpPostWindow httpPostWindow = new HttpPostWindow();
            httpPostWindow.Owner = mainWindow;

            JObject paramJSON = new JObject();
            paramJSON.Add("driverCard", cardCode);
            paramJSON.Add("operation", "forMakeCard");
            httpPostWindow.setParamObject(paramJSON);

            httpPostWindow.setOperation(HttpPostWindow.OperationType.getBillByCard.ToString());
            bool result = (bool)httpPostWindow.ShowDialog();
            if (!result)
            {
                string message = httpPostWindow.getMessage();
                if (null == message || "".Equals(message))
                {
                    message = "未查询到单据";
                }
                speech.Speak(message, SpeechVoiceSpeakFlags.SVSFlagsAsync);

                showMessage(message);

                return;
            }
            //mainWindow.Speak("请核对信息，确认正常后点击报道按钮。报道完成后，请取走身份证");

            //将卡片移动至读卡区域
            //App.getGlobalVariables().cardDeviceComm.SendHexData("F2 00 00 03 43 32 31 03 B2");
            //CardDeviceUtil.MoveCardToReadPosition();

            JObject resultObject = httpPostWindow.getResultObject();
            BillModel billModel = JsonConvert.DeserializeObject<BillModel>(resultObject.ToString());
            if ("0".Equals(billModel.Type))
            {
                billModel.Type = "销售业务";
            }
            else if ("1".Equals(billModel.Type))
            {
                billModel.Type = "采购业务";
            }
            else if ("2".Equals(billModel.Type))
            {
                billModel.Type = "销售退货业务";
            }
            else if ("3".Equals(billModel.Type))
            {
                billModel.Type = "采购退货业务";
            }


            ConfirmPage card = new ConfirmPage(billModel, mainWindow);
            if (null != image)
            {
                //card.setPersonImage(image);
            }
            NavigationService.GetNavigationService(this).Navigate(card);

        }

        private void QrPrint(object sender, RoutedEventArgs e)
        {
           // InputWindow inputWindow = new InputWindow();
           // inputWindow.Show();
           QrPrint qrpPrint = new QrPrint(mainWindow);
           NavigationService.GetNavigationService(this).Navigate(qrpPrint);

        }
     



        private void ReplaceCard(object sender, RoutedEventArgs e)
        {
            ReplaceCard replaceCard=new ReplaceCard(mainWindow);
            NavigationService.GetNavigationService(this).Navigate(replaceCard);
        }
    }
}
